#include <QHeaderView>
#include "treeview.h"

TreeView::TreeView(TreeModel *model, QWidget *parent)
    : QTreeView(parent), m_model(model)
{
    setModel(model);

    setExpandsOnDoubleClick(true);

    setSortingEnabled(true);
    sortByColumn(TIPUtils::getPropIndex(TIP::PID), Qt::AscendingOrder);

    setTreePosition(TIPUtils::getPropIndex(TIP::NAME));
    setIndentation(12);

    setPropWith(TIP::PID, 50);
    setPropWith(TIP::NAME, 200);
    setPropWith(TIP::STATE, 50);
    setPropWith(TIP::VM_PRIVATE, 70);
    setPropWith(TIP::VM_RESIDENT, 70);
    setPropWith(TIP::VM_SHARED, 70);
    setPropWith(TIP::VM_SIZE, 70);
    setPropWith(TIP::CPU_USAGE, 60);
    setPropWith(TIP::NICE, 40);

    setPropShown(TIP::PPID, false);
    setPropShown(TIP::CPU_TIME, false);
    setPropShown(TIP::VM_SIZE, false);
    setPropShown(TIP::VM_RESIDENT, false);
    setPropShown(TIP::VM_SHARED, false);
    setPropShown(TIP::CMD, false);


    connect(model, &TreeModel::beforeSort, [this]{
        m_current_task = pid_t(currentIndex().internalId());
    });

    connect(model, &TreeModel::afterSort, [this]{
        QModelIndex index = m_model->getIndexByPid(m_current_task);
        if (index.isValid()) {
            setCurrentIndex(index);
            scrollTo(index, QTreeView::PositionAtTop);
        }
    });
}

pid_t TreeView::getCurrentPid() const
{
    return pid_t(currentIndex().internalId());
}

void TreeView::setPropShown(TIP prop, bool shown)
{
    setColumnHidden(TIPUtils::getPropIndex(prop), !shown);
    emit onPropShownToggled(prop, shown);
}

bool TreeView::isPropShown(TIP prop)
{
    return !isColumnHidden(TIPUtils::getPropIndex(prop));
}

void TreeView::setPropWith(TIP prop, int width)
{
    if (width > 0) {
        setColumnWidth(TIPUtils::getPropIndex(prop), width);
    }
}
